try:
    import psutil
except ImportError:
    import subprocess
    import sys
    print("未找到psutil库，正在从清华大学镜像源安装...")
    try:
        subprocess.check_call([sys.executable, "-m", "pip", "install", "psutil", "-i", "https://pypi.tuna.tsinghua.edu.cn/simple"])
        import psutil
        print("psutil库安装成功。")
    except subprocess.CalledProcessError:
        print("安装psutil库时出错，请手动检查并安装。")


def get_parent_processes(pid):
    process_list = []
    try:
        # 获取当前进程对象
        process = psutil.Process(pid)
        while process:
            process_list.insert(0, process)
            try:
                # 获取父进程对象
                parent = process.parent()
                if parent and parent.pid != 0:
                    process = parent
                else:
                    break
            except (psutil.NoSuchProcess, psutil.AccessDenied, psutil.ZombieProcess):
                break
    except (psutil.NoSuchProcess, psutil.AccessDenied, psutil.ZombieProcess):
        pass
    return process_list

def display_processes(process_list):
    import datetime
    indent = 0
    for i, process in enumerate(process_list):
        # 获取父进程ID，如果没有父进程则为None
        parent_pid = process.parent().pid if process.parent() else "None"
        # 将创建时间戳转换为指定格式的日期时间字符串
        create_time = datetime.datetime.fromtimestamp(process.create_time()).strftime('%Y-%m-%d %H:%M:%S')
        prefix = "" if i == 0 else "└> "
        # print(" " * indent + f"{prefix}{process.name()}\t\t{process.pid}\t\t父 {parent_pid}\t\t{create_time}")
        print(f"{prefix}{process.name()}\t\t{process.pid}\t\t父 {parent_pid}\t\t{create_time}")
        indent += 1

if __name__ == "__main__":
    while True:
        try:
            pid = int(input("请输入进程ID（输入 'q' 退出）: "))
            print("=" * 80)
            parent_processes = get_parent_processes(pid)
            display_processes(parent_processes)
            print("=" * 80)
        except ValueError:
            user_input = input("输入无效，请输入有效的整数进程ID。若要退出，请输入 'q': ")
            if user_input.lower() == 'q':
                break
